package com.sdy.healthcode.h5.interceptor;

import com.sdy.common.model.Response;
import com.sdy.healthcode.biz.model.User;
import com.sdy.healthcode.biz.service.UserService;
import com.sdy.mvc.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 驾驶舱权限校验
 */
@Component
@Slf4j
public class AuthCockpitInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private UserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Integer userId = (Integer) request.getSession().getAttribute(com.sdy.common.constant.Constants.SESSION_USER_ID);
        if (userId == null) {
            return reject(response, null, Response.Code.noAuthorization);
        }
        User user = userService.getById(userId);
        if (user == null) {
            return reject(response, null, Response.Code.noAuthorization);
        }
        if (!user.getAuthCockpit().equals(1)) {
            return reject(response, null, Response.Code.noAuthorization);
        }
        return true;
    }

    private boolean reject(HttpServletResponse response, String errorInfo, Integer errorCode) throws IOException {
        String respJson = JsonUtil.toJson(Response.error(errorInfo, errorCode));
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(respJson == null ? "" : respJson);
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }
}
